from pymongo import UpdateOne

from zc_core.client.mongo_client import Mongo
from zc_core.util.common import parse_time
from zc_core.util.encrypt_util import md5

mongo = Mongo()


def fix_order():
    update_bulk = list()
    order_list = mongo.list('order_2020', query={'orderTime': {'$gte': parse_time('2020-06-25 0:00:00')}})
    for order in order_list:
        _id = order.get('_id')
        order_user = order.get('orderUser')
        if order_user and '*' not in order_user:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
                '_id': _id,
                'orderUser': None,
                'orderDept': order_user,
                'deptId': md5(order_user),
                'fix': '20200703',
            }}, upsert=False))

    print(len(update_bulk))
    mongo.bulk_write('order_2020', update_bulk)
    print('任务完成~')


def fix_order_item(year_month):
    update_bulk = list()
    order_list = mongo.list('order_item_{}'.format(year_month), query={'orderTime': {'$gte': parse_time('2020-06-25 0:00:00')}})
    for order in order_list:
        _id = order.get('_id')
        order_user = order.get('orderUser')
        if '*' not in order_user:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
                '_id': _id,
                'orderUser': None,
                'orderDept': order_user,
                'deptId': md5(order_user),
                'fix': '20200703',
            }}, upsert=False))

    print(len(update_bulk))
    mongo.bulk_write('order_item_{}'.format(year_month), update_bulk)
    print('任务完成~')


def fix_order_item2(year_month):
    update_bulk = list()
    order_list = mongo.list('order_item_{}_bak'.format(year_month))
    for order in order_list:
        _id = order.get('_id')
        order_dept = order.get('orderDept')
        order['deptId'] = md5(order_dept)
        if order_dept:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': order}, upsert=True))

    print(len(update_bulk))
    mongo.bulk_write('order_item_{}'.format(year_month), update_bulk)
    print('任务完成~')


if __name__ == '__main__':
    # fix_order()
    fix_order_item2('202101')
    fix_order_item2('202102')
    fix_order_item2('202103')
    fix_order_item2('202104')
